<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Models\Area as AreaModel;
use App\Services\Code\HttpResponse;
use Closure;

class UserLocationCityCheck
{
    public function handle($request, Closure $next)
    {
        $userRequestCityId = (int) $request->input('city_id');
        if (!$userRequestCityId) {
            return response()->json(HttpResponse::respFail(HttpResponse::CODE_CITY_ID_MISSING, 'param city_id missing'));
        }
        $cities = array_column((new AreaModel())->getCities(), 'id');
        if (!in_array($userRequestCityId, $cities)) {
            return response()->json(HttpResponse::respFail(HttpResponse::CODE_CITY_ID_INVALID, 'param city_id invalid'));
        }
        return $next($request);
    }
}
